import React, { useState, useEffect } from 'react';
import {
  Container,
  Grid,
  Paper,
  Typography,
  Avatar,
  Box,
  Button,
  TextField,
  Divider,
  Chip,
  CircularProgress,
  Alert,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Card,
  CardContent,
  LinearProgress,
  IconButton,
  ImageList,
  ImageListItem,
  Tabs,
  Tab,
  useTheme,
  alpha
} from '@mui/material';
import {
  Edit as EditIcon,
  Save as SaveIcon,
  Person as PersonIcon,
  Email as EmailIcon,
  EmojiEvents as TrophyIcon,
  AddPhotoAlternate as AddPhotoIcon,
  Delete as DeleteIcon,
  LocalActivity as LocalActivityIcon,
  Leaderboard as LeaderboardIcon,
  Favorite as FavoriteIcon,
  Nature as NatureIcon,
  FormatListBulleted as ListIcon
} from '@mui/icons-material';
import { useAuth } from '../contexts/AuthContext';
import axios from 'axios';
import {
  Timeline,
  TimelineItem,
  TimelineSeparator,
  TimelineConnector,
  TimelineContent,
  TimelineDot
} from '@mui/lab';
import { useResources } from '../contexts/ResourceContext';
import { useNavigate } from 'react-router-dom';
import CheckinDialog from '../components/CheckinDialog';
import ActivityCard from '../components/ActivityCard';
import CheckInModule from '../components/CheckInModule';
import FriendsModule from '../components/FriendsModule';

function Profile() {
  const theme = useTheme();
  const { user, token } = useAuth();
  const { userActivities, fetchUserActivities } = useResources();
  const [profileData, setProfileData] = useState(null);
  const [loading, setLoading] = useState(false);
  const [editDialogOpen, setEditDialogOpen] = useState(false);
  const [editedUser, setEditedUser] = useState({});
  const [success, setSuccess] = useState('');
  const [error, setError] = useState('');
  const [tabValue, setTabValue] = useState(0);
  const [stats, setStats] = useState({
    totalActivities: 0,
    totalPoints: 0,
    completedChallenges: 0,
    carbonSaved: 0,
    rank: '新手环保者'
  });
  const [checkInDialogOpen, setCheckInDialogOpen] = useState(false);
  const [selectedActivity, setSelectedActivity] = useState(null);

  // 获取用户资料
  const fetchProfileData = async () => {
    try {
      setLoading(true);
      // 使用当前用户数据作为备选
      if (user) {
        setProfileData(user);
        setEditedUser({
          username: user.username || '',
          email: user.email || '',
          bio: user.bio || '',
        });
      }
      
      // 尝试获取更详细的用户数据
      if (token) {
        try {
          const response = await axios.get('/api/users/me');
          if (response.data) {
            setProfileData(response.data);
            setEditedUser({
              username: response.data.username || '',
              email: response.data.email || '',
              bio: response.data.bio || '',
            });
          }
        } catch (err) {
          console.log('获取详细用户数据失败，使用基本用户数据');
        }
      }
      
      // 获取用户统计数据
      try {
        if (user && user._id) {
          const statsResponse = await axios.get(`/api/users/${user._id}/stats`);
          if (statsResponse.data) {
            setStats({
              totalActivities: statsResponse.data.totalActivities || 0,
              totalPoints: statsResponse.data.points || 0,
              completedChallenges: statsResponse.data.completedChallenges || 0,
              carbonSaved: statsResponse.data.carbonSaved || 0,
              rank: statsResponse.data.rank || '新手环保者'
            });
          }
        }
      } catch (err) {
        console.log('获取用户统计数据失败');
        // 使用默认统计数据
        setStats({
          totalActivities: userActivities?.length || 0,
          totalPoints: user?.points || 0,
          completedChallenges: user?.completedChallenges?.length || 0,
          carbonSaved: user?.carbonSaved || 0,
          rank: '环保爱好者'
        });
      }
    } catch (error) {
      console.error('获取数据失败:', error);
      setError('获取用户数据失败，请稍后再试');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchProfileData();
    if (user) {
      fetchUserActivities();
    }
    
    // 如果没有活动数据，尝试获取一些示例活动
    if (!userActivities || userActivities.length === 0) {
      // 设置一些示例活动数据，以便页面能够正常显示
      const sampleActivities = [
        {
          _id: '1',
          title: '植树活动',
          description: '参与社区植树活动，为环境贡献一份力量。',
          progress: 60,
          remainingDays: 5,
          status: '进行中'
        },
        {
          _id: '2',
          title: '垃圾分类挑战',
          description: '连续30天正确进行垃圾分类，培养环保习惯。',
          progress: 40,
          remainingDays: 18,
          status: '进行中'
        }
      ];
      
      // 这里可以根据需要设置示例活动
    }
  }, []);

  const handleEditSubmit = async () => {
    try {
      setLoading(true);
      const response = await axios.put('/api/users/profile', editedUser);
      setProfileData(response.data);
      setEditDialogOpen(false);
      setSuccess('个人资料更新成功');
    } catch (error) {
      console.error('更新个人资料失败:', error);
      setError('更新个人资料失败，请稍后再试');
    } finally {
      setLoading(false);
    }
  };

  const handleTabChange = (event, newValue) => {
    setTabValue(newValue);
  };

  // 添加打卡对话框打开函数
  const openCheckInDialog = (activity) => {
    setSelectedActivity(activity);
    setCheckInDialogOpen(true);
  };

  // 如果用户未登录，显示提示信息
  if (!user) {
    return (
      <Container maxWidth="lg">
        <Box sx={{ py: 4, textAlign: 'center' }}>
          <Alert severity="info">请先登录以查看个人主页</Alert>
        </Box>
      </Container>
    );
  }

  return (
    <Container maxWidth="lg">
      <Box sx={{ py: 4 }}>
        {/* 个人信息卡片 */}
        <Paper 
          elevation={3} 
          sx={{ 
            p: 3, 
            mb: 3, 
            borderRadius: 2,
            background: `linear-gradient(to right, ${alpha(theme.palette.primary.light, 0.1)}, ${alpha(theme.palette.primary.main, 0.05)})`,
            position: 'relative'
          }}
        >
          <IconButton 
            sx={{ position: 'absolute', top: 16, right: 16 }}
            onClick={() => setEditDialogOpen(true)}
          >
            <EditIcon />
          </IconButton>

          <Grid container spacing={3} alignItems="center">
            <Grid item xs={12} sm={3} sx={{ textAlign: { xs: 'center', sm: 'left' } }}>
              <Avatar
                src={profileData?.avatar}
                sx={{ 
                  width: 120, 
                  height: 120, 
                  mx: { xs: 'auto', sm: 0 },
                  border: `4px solid ${theme.palette.primary.main}`,
                  boxShadow: theme.shadows[3]
                }}
              >
                {profileData?.username?.charAt(0).toUpperCase() || 'U'}
              </Avatar>
            </Grid>
            
            <Grid item xs={12} sm={9}>
              <Typography variant="h4" gutterBottom>
                {profileData?.username || '用户名'}
              </Typography>
              
              <Box sx={{ display: 'flex', alignItems: 'center', mb: 1 }}>
                <EmailIcon sx={{ mr: 1, color: 'text.secondary' }} />
                <Typography variant="body1" color="text.secondary">
                  {profileData?.email || 'email@example.com'}
                </Typography>
              </Box>
              
              <Typography variant="body1" sx={{ mt: 2, mb: 2 }}>
                {profileData?.bio || '这个用户还没有添加个人简介...'}
              </Typography>
              
              <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1, mt: 2 }}>
                <Chip 
                  icon={<TrophyIcon />} 
                  label={`${stats.rank}`} 
                  color="primary" 
                />
                <Chip 
                  icon={<LocalActivityIcon />} 
                  label={`${stats.totalPoints} 积分`} 
                  variant="outlined" 
                />
              </Box>
            </Grid>
          </Grid>
        </Paper>

        {/* 统计数据卡片 */}
        <Grid container spacing={3} sx={{ mb: 3 }}>
          <Grid item xs={6} sm={3}>
            <Card 
              elevation={2} 
              sx={{ 
                borderRadius: 2,
                height: '100%',
                transition: 'transform 0.2s',
                '&:hover': {
                  transform: 'translateY(-5px)',
                  boxShadow: theme.shadows[8]
                }
              }}
            >
              <CardContent sx={{ textAlign: 'center' }}>
                <LocalActivityIcon color="primary" sx={{ fontSize: 40, mb: 1 }} />
                <Typography variant="h4" color="primary">
                  {stats.totalPoints}
                </Typography>
                <Typography variant="body2" color="text.secondary">
                  环保积分
                </Typography>
              </CardContent>
            </Card>
          </Grid>
          
          <Grid item xs={6} sm={3}>
            <Card 
              elevation={2} 
              sx={{ 
                borderRadius: 2,
                height: '100%',
                transition: 'transform 0.2s',
                '&:hover': {
                  transform: 'translateY(-5px)',
                  boxShadow: theme.shadows[8]
                }
              }}
            >
              <CardContent sx={{ textAlign: 'center' }}>
                <TrophyIcon color="secondary" sx={{ fontSize: 40, mb: 1 }} />
                <Typography variant="h4" color="secondary">
                  {stats.completedChallenges}
                </Typography>
                <Typography variant="body2" color="text.secondary">
                  完成挑战
                </Typography>
              </CardContent>
            </Card>
          </Grid>
          
          <Grid item xs={6} sm={3}>
            <Card 
              elevation={2} 
              sx={{ 
                borderRadius: 2,
                height: '100%',
                transition: 'transform 0.2s',
                '&:hover': {
                  transform: 'translateY(-5px)',
                  boxShadow: theme.shadows[8]
                }
              }}
            >
              <CardContent sx={{ textAlign: 'center' }}>
                <NatureIcon color="success" sx={{ fontSize: 40, mb: 1 }} />
                <Typography variant="h4" color="success.main">
                  {stats.carbonSaved}
                </Typography>
                <Typography variant="body2" color="text.secondary">
                  减少碳排放(kg)
                </Typography>
              </CardContent>
            </Card>
          </Grid>
          
          <Grid item xs={6} sm={3}>
            <Card 
              elevation={2} 
              sx={{ 
                borderRadius: 2,
                height: '100%',
                transition: 'transform 0.2s',
                '&:hover': {
                  transform: 'translateY(-5px)',
                  boxShadow: theme.shadows[8]
                }
              }}
            >
              <CardContent sx={{ textAlign: 'center' }}>
                <LeaderboardIcon color="info" sx={{ fontSize: 40, mb: 1 }} />
                <Typography variant="h4" color="info.main">
                  {stats.totalActivities}
                </Typography>
                <Typography variant="body2" color="text.secondary">
                  参与活动
                </Typography>
              </CardContent>
            </Card>
          </Grid>
        </Grid>

        {/* 标签页内容 */}
        <Paper elevation={2} sx={{ borderRadius: 2, overflow: 'hidden' }}>
          <Tabs 
            value={tabValue} 
            onChange={handleTabChange}
            variant="fullWidth"
            sx={{ 
              borderBottom: 1, 
              borderColor: 'divider',
              background: alpha(theme.palette.primary.main, 0.05)
            }}
          >
            <Tab 
              icon={<NatureIcon />} 
              label="环保活动" 
              iconPosition="start"
              sx={{ py: 2 }}
            />
            <Tab 
              icon={<ListIcon />} 
              label="打卡记录" 
              iconPosition="start"
              sx={{ py: 2 }}
            />
            <Tab 
              icon={<PersonIcon />} 
              label="好友" 
              iconPosition="start"
              sx={{ py: 2 }}
            />
          </Tabs>
          
          {/* 环保活动标签页 */}
          <Box sx={{ p: 3, display: tabValue === 0 ? 'block' : 'none' }}>
            {userActivities && userActivities.length > 0 ? (
              <Grid container spacing={2}>
                {userActivities.map(activity => (
                  <Grid item xs={12} sm={6} md={4} key={activity._id}>
                    <Card sx={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
                      <CardContent sx={{ flexGrow: 1 }}>
                        <Typography variant="h6" gutterBottom>
                          {activity.title}
                        </Typography>
                        <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
                          {activity.description?.substring(0, 100)}...
                        </Typography>
                        <LinearProgress 
                          variant="determinate" 
                          value={activity.progress || 0} 
                          sx={{ mb: 1, height: 8, borderRadius: 4 }}
                        />
                        <Typography variant="caption" color="text.secondary">
                          进度: {Math.round(activity.progress || 0)}%
                        </Typography>
                        <Box sx={{ mt: 2 }}>
                          <Chip 
                            size="small" 
                            label={`${activity.checkins?.length || 0}/${activity.checkInRequired} 次打卡`} 
                            color="primary" 
                            variant="outlined"
                          />
                        </Box>
                      </CardContent>
                      <Box sx={{ p: 2, pt: 0 }}>
                        <Button 
                          variant="contained" 
                          fullWidth
                          onClick={() => openCheckInDialog(activity)}
                          disabled={activity.progress >= 100}
                        >
                          {activity.progress >= 100 ? '已完成' : '打卡'}
                        </Button>
                      </Box>
                    </Card>
                  </Grid>
                ))}
              </Grid>
            ) : (
              <Box sx={{ textAlign: 'center', py: 4 }}>
                <Typography variant="body1" color="text.secondary">
                  您还没有参与任何环保活动
                </Typography>
                <Button 
                  variant="contained" 
                  sx={{ mt: 2 }}
                  href="/activities"
                >
                  浏览活动
                </Button>
              </Box>
            )}
          </Box>
          
          {/* 打卡记录标签页 */}
          <Box sx={{ p: 3, display: tabValue === 1 ? 'block' : 'none' }}>
            <CheckInModule />
          </Box>
          
          {/* 好友标签页 */}
          <Box sx={{ p: 3, display: tabValue === 2 ? 'block' : 'none' }}>
            <FriendsModule />
          </Box>
        </Paper>

        {/* 编辑个人资料对话框 */}
        <Dialog open={editDialogOpen} onClose={() => setEditDialogOpen(false)} maxWidth="sm" fullWidth>
          <DialogTitle>编辑个人资料</DialogTitle>
          <DialogContent>
            <Box sx={{ pt: 1 }}>
              <TextField
                fullWidth
                margin="normal"
                label="用户名"
                value={editedUser.username || ''}
                onChange={(e) => setEditedUser({ ...editedUser, username: e.target.value })}
              />
              <TextField
                fullWidth
                margin="normal"
                label="电子邮箱"
                value={editedUser.email || ''}
                onChange={(e) => setEditedUser({ ...editedUser, email: e.target.value })}
              />
              <TextField
                fullWidth
                margin="normal"
                label="个人简介"
                multiline
                rows={4}
                value={editedUser.bio || ''}
                onChange={(e) => setEditedUser({ ...editedUser, bio: e.target.value })}
              />
              <Box sx={{ mt: 2, display: 'flex', justifyContent: 'center' }}>
                <Button
                  variant="outlined"
                  component="label"
                  startIcon={<AddPhotoIcon />}
                >
                  更换头像
                  <input
                    type="file"
                    hidden
                    accept="image/*"
                  />
                </Button>
              </Box>
            </Box>
          </DialogContent>
          <DialogActions>
            <Button onClick={() => setEditDialogOpen(false)}>取消</Button>
            <Button
              onClick={handleEditSubmit}
              variant="contained"
              disabled={loading}
              startIcon={loading ? <CircularProgress size={20} /> : <SaveIcon />}
            >
              保存
            </Button>
          </DialogActions>
        </Dialog>

        {/* 打卡对话框 */}
        {selectedActivity && (
          <CheckInModule 
            open={checkInDialogOpen}
            activity={selectedActivity}
            onClose={() => setCheckInDialogOpen(false)}
            onSuccess={() => {
              setCheckInDialogOpen(false);
              fetchUserActivities();
              setSuccess('打卡成功！');
            }}
          />
        )}

        {/* 消息提示 */}
        {success && (
          <Alert
            severity="success"
            onClose={() => setSuccess('')}
            sx={{ position: 'fixed', bottom: 16, right: 16, zIndex: 2000 }}
          >
            {success}
          </Alert>
        )}
        
        {error && (
          <Alert
            severity="error"
            onClose={() => setError('')}
            sx={{ position: 'fixed', bottom: 16, right: 16, zIndex: 2000 }}
          >
            {error}
          </Alert>
        )}
      </Box>
    </Container>
  );
}

export default Profile; 